package com.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class Upload2Servlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		/*
		 * 1.创建工厂
		 * 2.创建Servlet解析器
		 * 3.使用解析器解析request，得到FileItem集合
		 */
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		try {
			List<FileItem> fileItemList = sfu.parseRequest(request);
			System.out.println("普通表单项名：" + fileItemList.get(0).getFieldName());
			System.out.println("普通表单项值：" + fileItemList.get(0).getString("UTF-8"));//参数设置字符编码
			System.out.println("文件表单项：");
			System.out.println("Content-Type:" + fileItemList.get(1).getContentType());
			System.out.println("filename:" + fileItemList.get(1).getName());
			System.out.println("filesize:" + fileItemList.get(1).getSize());
			File destFile = new java.io.File("D:\\乔祥耀.jpg");
			fileItemList.get(1).write(destFile);
		} catch (FileUploadException e) {
			throw new RuntimeException(e); 
		} catch (Exception e) {
			throw new RuntimeException(e); 
		}
	}

}

